package com.Xsoft.ShoppingList;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.view.inputmethod.InputMethodManager;

import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MyshoppinglistActivity extends Activity {
	private static final int CREATE_NEW_PRODUCT_LIST_MENU_ITEM_ID = 4;
	private final String TEXT_EDIT_LAST_ENTERED_TEXT_KEY = "Last entered product name";
	private final String MY_PREFS_KEY = "My prefs";
	private final int ADD_PRODUCT_MENU_ITEM_ID = 0;
	private final int REMOVE_PRODUCT_MENU_ITEM_ID = 1;
	private final int REMOVE_SELECTED_PRODUCTS_MENU_ITEM_ID = 2;
	private final int PICK_PRODUCTS_FROM_LIST_MENU_ITEM_ID = 3;
	private final int PICK_PRODUCTS_FROM_LIST_ACTIVITY_ID = 0;
	private ShoppingListBDAdapter bdAdapter;
	Resources resources;
	ArrayList<Product> productList;
	ProductArrayAdapter aa;
	EditText editText;
	Product currentProduct;
	InputMethodManager inputManager;

	private ListView listView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.main);
		productList = new ArrayList<Product>();
		resources = getResources();
		resources.getString(R.string.hello);
		listView = (ListView) findViewById(R.id.listViewProduct);
		int resID = R.layout.list_item;
		aa = new ProductArrayAdapter(this, resID, productList);
		listView.setAdapter(aa);
		editText = (EditText) findViewById(R.id.editTextProduct);
		// /editText.setVisibility(EditText.GONE);
		editText.setFocusableInTouchMode(true);

		// editText.setFocusable(true);
		editText.setSelected(true);
		inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		editText.setFocusableInTouchMode(true);
		bdAdapter = new ShoppingListBDAdapter(getApplicationContext());
		bdAdapter.open();
		RestoreUIState();
		RestoreProductList();
		@SuppressWarnings("unused")
		TextView tw = new TextView(this);
		// RestoreProductList();
		// listView.setSelection(2);
		// listView.setSelected(true);
		// CharSequence tmpStr =
		// savedInstanceState.getCharSequence(TEXT_EDIT_LAST_ENTERED_TEXT_KEY);
		// if(tmpStr!=null)
		{
			// editText.setText(tmpStr);
		}
		editText.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				@SuppressWarnings("unused")
				String tmpStr;
				switch (keyCode) {
				case KeyEvent.KEYCODE_DPAD_CENTER:
					inputManager.hideSoftInputFromWindow(
							editText.getWindowToken(), 0);
					if ((event.getAction() == KeyEvent.ACTION_DOWN)
							&& (!editText.getText().toString().equals(""))) {
						currentProduct = new Product(editText.getText()
								.toString(), false, true);
						AddProduct(currentProduct);
						// inputManager.hideSoftInputFromWindow(editText.getWindowToken(),
						// 0);
						// editText.clearFocus();

					}
				}
				// TODO Auto-generated method stub
				return false;
			}

		});
		registerForContextMenu(listView);
		super.onCreate(savedInstanceState);

	}

	private void RestoreProductList() {
		// startManagingCursor(bdCursor);
		// bdCursor.
		bdAdapter.open();
		ArrayList<Product> tmpProductList = bdAdapter.getAllroducts();
		Iterator<Product> tmpIt = tmpProductList.iterator();
		Product tmpProduct;
		productList.clear();
		while (tmpIt.hasNext()) {
			tmpProduct = tmpIt.next();
			if ((tmpProduct.isInList() == true)){
					bdAdapter.updateProduct(tmpProduct);
					//tmpProduct.setBought(false);
					aa.add(tmpProduct);
			}
		}
		aa.notifyDataSetChanged();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		//
		SaveUIState();
	//	bdAdapter.close();
		bdAdapter.updateProductList(productList);
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// editText.setText(savedInstanceState.getCharSequence(TEXT_EDIT_LAST_ENTERED_TEXT_KEY));
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		SaveUIState();
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onResume() {
		RestoreUIState();
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// editText.requestFocus();
		inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	void RestoreUIState() {
		SharedPreferences shp = getSharedPreferences(MY_PREFS_KEY, MODE_PRIVATE);
		editText.setText(shp.getString(TEXT_EDIT_LAST_ENTERED_TEXT_KEY, null));
		// RestoreProductList();

	}

	void SaveUIState() {
		SharedPreferences shP = getSharedPreferences(MY_PREFS_KEY,
				Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = shP.edit();
		editor.putString(TEXT_EDIT_LAST_ENTERED_TEXT_KEY, editText.getText()
				.toString());
		// Commit the preferences.
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuItem addItem = menu.add(0, ADD_PRODUCT_MENU_ITEM_ID, Menu.NONE,
				R.string.add_menu_item);
		MenuItem removeItem = menu.add(0, REMOVE_PRODUCT_MENU_ITEM_ID,
				Menu.NONE, R.string.remove_menu_item);
		addItem.setIcon(R.drawable.add_product);
		removeItem.setIcon(R.drawable.remove_product);
		MenuItem removeSelectedItem = menu.add(0,
				REMOVE_SELECTED_PRODUCTS_MENU_ITEM_ID, Menu.NONE,
				R.string.remove_selected_items);
		removeSelectedItem.setIcon(R.drawable.delete_selected);
		MenuItem pickProductsFromList = menu.add(0,
				PICK_PRODUCTS_FROM_LIST_MENU_ITEM_ID, Menu.NONE,
				R.string.pick_items_from_list);
		pickProductsFromList.setIcon(R.drawable.pick_from_list);
		
		MenuItem createNewList = menu.add(0,
				CREATE_NEW_PRODUCT_LIST_MENU_ITEM_ID, Menu.NONE,
				R.string.create_new_list_menu_item);
		createNewList.setIcon(R.drawable.new_list);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		int selectedListId = listView.getSelectedItemPosition();
		MenuItem removeItem = menu.findItem(REMOVE_PRODUCT_MENU_ITEM_ID);
		removeItem.setVisible(selectedListId > -1);
		MenuItem addToListItem =menu.findItem(ADD_PRODUCT_MENU_ITEM_ID);
		addToListItem.setVisible(!editText.getText().toString().equals(""));
		MenuItem removeSelectedProdFromListItem =menu.findItem(REMOVE_SELECTED_PRODUCTS_MENU_ITEM_ID);
		removeSelectedProdFromListItem.setVisible(aa.getCheckedItemsNum()>0);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String prodName;
		switch (item.getItemId()) {
		case ADD_PRODUCT_MENU_ITEM_ID:
			editText.setVisibility(EditText.VISIBLE);
			prodName = editText.getText().toString();
			editText.requestFocus();
			if (!prodName.equals("")) {
				currentProduct = new Product(prodName,false,true);
				AddProduct(currentProduct);
			}
			break;
		case REMOVE_PRODUCT_MENU_ITEM_ID:
			RemoveProduct(listView.getSelectedItemPosition());
			break;
		case REMOVE_SELECTED_PRODUCTS_MENU_ITEM_ID:
			RemoveSelectedProducts();
			break;
		case PICK_PRODUCTS_FROM_LIST_MENU_ITEM_ID:
			Intent intent = new Intent("com.Xsoft.ShoppingList.PRODUCT_PICKER");
			startActivityForResult(intent, PICK_PRODUCTS_FROM_LIST_ACTIVITY_ID);
			break;
		case CREATE_NEW_PRODUCT_LIST_MENU_ITEM_ID:
			RemoveAllProducts();
			break;

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_PRODUCTS_FROM_LIST_ACTIVITY_ID:
			bdAdapter.open();
			RestoreProductList();
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// menu.setHeaderTitle();
		MenuItem removeItem = menu.add(0, REMOVE_PRODUCT_MENU_ITEM_ID,
				Menu.NONE, R.string.remove_menu_item);
		removeItem.setIcon(R.drawable.remove_product);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		super.onContextItemSelected(item);
		AdapterView.AdapterContextMenuInfo menuInfo;
		menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		int selectedItem = menuInfo.position;
		switch (item.getItemId()) {
		case REMOVE_PRODUCT_MENU_ITEM_ID:
			RemoveProduct(selectedItem);
			break;
		}
		return true;
	}

	private void AddProduct(Product product) {
		aa.add(product);
		aa.notifyDataSetChanged();
		bdAdapter.insertProduct(product);
		editText.setText("");

	}

	private com.Xsoft.ShoppingList.ActivityResult RemoveProduct(int prodInListId) {
		Product tmpProd =productList.get(prodInListId);
		tmpProd.toProductList(false);
		tmpProd.setBought(false);
		bdAdapter.updateProduct(tmpProd);
		productList.remove(prodInListId);
		aa.notifyDataSetChanged();
		return com.Xsoft.ShoppingList.ActivityResult.RESULT_OK;
	}

	private com.Xsoft.ShoppingList.ActivityResult RemoveSelectedProducts() {
		Iterator<Product> it = productList.iterator();
		Product tmpProd;
		while (it.hasNext()) {
			tmpProd = it.next();
			
			if (tmpProd.isBought()) {
				tmpProd.toProductList(false);
				tmpProd.setBought(false);
				//bdAdapter.updateProduct(1,tmpProd);
				
				bdAdapter.updateProduct(tmpProd);
				it.remove();
			}
		}
		
		// bdAdapter.removeSelectedProducts();
		aa.notifyDataSetChanged();
		return com.Xsoft.ShoppingList.ActivityResult.RESULT_OK;
	}
	private com.Xsoft.ShoppingList.ActivityResult RemoveAllProducts() {
		Iterator<Product> it = productList.iterator();
		Product tmpProd;
		while (it.hasNext()) {
			tmpProd = it.next();
				tmpProd.toProductList(false);
				tmpProd.setBought(false);
				//bdAdapter.updateProduct(1,tmpProd);
				bdAdapter.updateProduct(tmpProd);
				it.remove();
		}
		aa.notifyDataSetChanged();
		return com.Xsoft.ShoppingList.ActivityResult.RESULT_OK;
	}
}